<?php

use \Mapper\ProtocolModel as ProtocolMapper;

class ProtocolController extends \Base\AbstractController {
    /**
     * @desc 协议的列表
     *
     */
    public function listAction() {
        $page = new \Lib\Paginator('protocol');
        $this->assign('count', $page->count());
        $this->assign('page', $page->getPage());
        $this->assign('perPage', $page->getPerpage());
        $this->assign('lists', $page->lists());
    }

    /**
     * @desc 编辑
     */
    public function editAction() {
        $request = $this->getRequest();
        $id      = (int)$request->get('id');
        $content = (string)trim($request->get('content'));
        $mapper  = ProtocolMapper::getInstance();
        $model   = $mapper->findById($id);

        if(!$model instanceof \ProtocolModel) {
            return false;
        }

        if($request->isPost()) {
            $model->setContent($content);
            $errMsg = $this->validate($model);

            if($errMsg !== false) {
                return \Response::errmsg($errMsg);
            }

            try {
                $rows = $mapper->update($model, ['id' => $id]);//插入数据库

                if($rows > 0) {
                    return \Response::msg();
                } elseif($rows == 0) {
                    return \Response::errmsg('信息未改动!');
                }
            } catch(\Exception $e) {
                return \Response::errmsg($e->getMessage());
            }
        }

        $this->assign('model', $model);
    }


    private function validate(\ProtocolModel $model) {
        if(empty($model->getTitle())) {
            return '标题不能为空';
        }

        if(empty($model->getContent())) {
            return '内容不能为空';
        }

        return false;
    }
}
